from django.shortcuts import render
from django.http import JsonResponse

from login.views import login_required
from login.models import UserInfo, UserRole
from .models import Tab
from .models import InformationFormData
from .serializer import InformationFormDataSerializer
import datetime
import json


# Create your views here.

@login_required
def index(request):
    '''
    首页
    :param request:
    :return:
    '''
    chineseName = UserInfo.objects.get(uname=request.session['userName']).description

    tab = Tab.objects.values()
    urole = UserRole.objects.get(id=UserInfo.objects.get(uname=request.session['userName']).urid_id).id
    rname = UserRole.objects.get(id=UserInfo.objects.get(uname=request.session['userName']).urid_id).rname

    return render(request, 'index.html',
                  context={'chineseName': chineseName, 'tab': tab, 'urole': urole, 'rname': rname})


@login_required
def informationReport(request):
    '''
    企业信息填报页面
    :param request:
    :return:
    '''
    userState = UserInfo.objects.get(uname=request.session['userName']).user_state
    return render(request, 'iframes/informationReport.html', context={'userState': userState, 'userName':
        request.session['userName']})


@login_required
def reportform(request):
    '''
    企业信息填报表单提交处理
    :param request:
    :return:
    '''
    postValueList = []
    fieldList = []
    dataList = {}
    for key in request.POST:
        postValueList.append(request.POST.get(key))
    postValueList.append(request.session['userName'])
    for field in InformationFormData._meta.get_fields():
        fieldList.append(field.name)

    informationData = InformationFormData()
    for key, value in zip(fieldList[1:], postValueList):
        dataList[key] = value
    dataPull = InformationFormData.objects.create(**dataList)
    dataPull.save()
    # 修改用户状态 判断是否已经填报信息
    userModel = UserInfo.objects.get(uname=request.session['userName'])
    userModel.user_state = 1
    userModel.save()
    return JsonResponse({'response': 1})


@login_required
def informationexport(request):
    '''
    企业信息导出成excel页面
    :param request:
    :return:
    '''
    return render(request, 'iframes/informationexport.html')


@login_required
def informationReview(request):
    '''
    企业信息审核页面
    :param request:
    :return:
    '''
    return render(request, 'iframes/informationReview.html')


@login_required
def informationModify(request):
    '''
    企业信息修改页面
    :param request:
    :return:
    '''

    form_id = request.GET.get('fId')
    info = InformationFormData.objects.get(id=form_id)
    return render(request, 'iframes/informationModify.html', context={"info": info})


@login_required
def modifyform(request):
    '''
    企业信息修改表单提交处理
    :param request:
    :return:
    '''

    postValueList = []
    fieldList = []
    dataList = {}
    fId = request.POST.get('fId')
    print(fId)
    for key in request.POST:
        postValueList.append(request.POST.get(key))
    postValueList.pop(-1)
    postValueList.append(request.session['userName'])
    for field in InformationFormData._meta.get_fields():
        fieldList.append(field.name)
    for key, value in zip(fieldList[1:], postValueList):
        dataList[key] = value

    info = InformationFormData.objects.get(id=fId)
    infoObject = InformationFormDataSerializer(data=dataList, instance=info)

    if infoObject.is_valid():
        infoObject.save()
        return JsonResponse({'response': 1})

    return JsonResponse({'response': 0})


@login_required
def informationexportData(request):
    '''
    获取数据转化成json数据传给前台
    :param request:
    :return:
    '''
    fieldList = []
    dataTempList = []
    total = InformationFormData.objects.count()
    for field in InformationFormData._meta.get_fields():
        fieldList.append(field.name)
    # 删除操作人字段信息
    # fieldList.pop(-2)
    # fieldList.pop(0)

    for data in InformationFormData.objects.values_list():
        data = list(data)
        # data.pop(-2)
        # data.pop(0)
        data[-2] = data[-2].strftime('%Y-%m-%d %H:%M:%S')
        if data[-1] == 0:
            data[-1] = '未审核'
        else:
            data[-1] = '已审核'
        dataTempList.append(data)

    dataList = []
    for x in dataTempList:
        aa = dict(zip(fieldList, x))
        dataList.append(aa)

    dataJson = {
        "total": total,
        "rows": dataList
    }
    return JsonResponse(dataJson, json_dumps_params={'ensure_ascii': False})


@login_required
def informationreviewData(request):
    '''
    获取数据转化成json数据传给前台
    :param request:
    :return:
    '''

    fieldList = []
    dataTempList = []
    uname = UserInfo.objects.get(uname=request.session['userName']).uname
    urid = UserInfo.objects.get(uname=request.session['userName']).urid_id

    for field in InformationFormData._meta.get_fields():
        fieldList.append(field.name)

    if urid == 1:
        total = InformationFormData.objects.count()
        dataTempList = infomationsList(InformationFormData.objects)
    else:
        Informationreview = InformationFormData.objects.filter(form_76=uname)
        total = Informationreview.count()
        dataTempList = infomationsList(Informationreview)

    dataList = []
    for x in dataTempList:
        aa = dict(zip(fieldList, x))
        dataList.append(aa)

    dataJson = {
        "total": total,
        "rows": dataList,
        'urid': urid,
    }
    return JsonResponse(dataJson, json_dumps_params={'ensure_ascii': False})


def infomationsList(objects):
    dataList = []
    for data in objects.values_list():
        data = list(data)
        data[-2] = data[-2].strftime('%Y-%m-%d %H:%M:%S')
        if data[-1] == 0:
            data[-1] = '未审核'
        else:
            data[-1] = '已审核'
        dataList.append(data)
    return dataList


@login_required
def informationApprove(request):
    fId = request.POST.get('formId')
    try:
        data = InformationFormData.objects.get(id=fId)
        data.form_78 = 1
        data.save()
        return JsonResponse({'response': 1})
    except ZeroDivisionError:
        return JsonResponse({'response': 0})
